import axios from 'axios'
import store from '@/store/index'
import router from '@/router/index'
import { Message } from 'element-ui'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    config.headers.Authorization = 'Bearer ' + store.state.user.token
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response.status === 401) {
      store.commit('user/remToken')
      router.push('/login')
      Message.error('用户登录已过期，请重新登录！')
    } else {
      Message.error(error.response.data.msg)
    }
    return Promise.reject(error)
  }
)

export default service
